class RangeBuilder

  # Usage:
  #  build_range( persons ){|person| person.age  }
  def self.build_range enum
    first, last = nil, nil
    comp_first, comp_last = nil, nil
    enum.each do |obj|
      comp = yield obj
      if first == nil || comp < comp_first
        first = obj
        comp_first = yield first
      end
      if last  == nil || comp > comp_last
        last  = obj
        comp_last = yield last
      end
    end
    [first, last]
  end

  # arg: sorted enum. elements must implement succ
  def self.build_from_sorted enum
    ranges = []
    return ranges if enum.empty?
    first = last = enum.first
    enum.each_cons(2) do |a,b|
      last = b
      if a.succ != b
        ranges << Range.new(first,a)
        first = b
      end
    end
    ranges << Range.new(first,last)
    ranges
  end
end
